import math

class Expr:
    def evaluate(self):
        return 0


class NonTerminalExpr(Expr):
    def __init__(self, op_expr):
        self.op_expr = op_expr


class TerminalExpr(Expr):
    def __init__(self, value):
        self.value = value


class AdditiveExpr(NonTerminalExpr):
    def evaluate(self):
        ret = self.op_expr.pop(0).evaluate()
        while len(self.op_expr) > 1:
            op = self.op_expr.pop(0)
            if op == '+':
                ret = ret + self.op_expr.pop(0).evaluate()
            elif op == '-':
                ret = ret - self.op_expr.pop(0).evaluate()
        return ret


class MultiplicativeExpr(NonTerminalExpr):
    def evaluate(self):
        ret = self.op_expr.pop(0).evaluate()
        while len(self.op_expr) > 1:
            op = self.op_expr.pop(0)
            if op == '*':
                ret = ret * self.op_expr.pop(0).evaluate()
            elif op == '/':
                ret = ret / self.op_expr.pop(0).evaluate()
        return ret

class FunctionCall(Expr):
    def __init__(self, fun, expr):
        self.fun = fun
        self.expr = expr
    def evaluate(self):
        return self.fun(self.expr.evaluate())


class IntegerLiteral(TerminalExpr):
    def __init__(self, value):
        TerminalExpr.__init__(self, value)
    def evaluate(self):
        return int(self.value)


class DecimalLiteral(TerminalExpr):
    def __init__(self, value):
        TerminalExpr.__init__(self, value)
    def evaluate(self):
        return float(self.value)


if __name__ == '__main__':
    expr = AdditiveExpr([
        MultiplicativeExpr([
            DecimalLiteral(100),
            '*',
            FunctionCall(math.sin,  # python的math.sin函数
                         AdditiveExpr([
                             IntegerLiteral(29),
                             '+',
                             MultiplicativeExpr([
                                 IntegerLiteral(23),
                                 '*',
                                 IntegerLiteral(6),
                             ])
                         ])
                         )
        ]),
        '+',
        FunctionCall(math.sqrt,  # python的math.sqrt函数
                     FunctionCall(math.cos,  # python的cos.sqrt函数
                                  MultiplicativeExpr([
                                      IntegerLiteral(34),
                                      '*',
                                      IntegerLiteral(5)
                                  ])
                                  )
                     )
    ])
    # 100.0*sin(29+(23*6))+sqrt(cos(34*5))=-46.5865
    print(expr.evaluate())